const app = getApp()
// 记录短信验证码
let my_Code = ''
let redirectURL = ''
Page({
  data: {
    countDownVisible: false,
    mobile: '',
    code: ''
  },
  onLoad(options) {
    console.log(redirectURL);
    redirectURL = options.redirectURL
  },
  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
  // 2.获取短信验证码
  async getCode() {
    // 2.1校验手机号码的格式
    if (!wx.verify.verifyMobile(this.data.mobile)) return
    // 2.2获取短信验证码
    const {
      code,
      data
    } = await wx.http.get("/code", {
      mobile: this.data.mobile
    })
    if (code !== 10000) wx.utils.toast('获取短信验证码失败，请重新获取')
    // 2.4记录短信验证码
    my_Code = data.code
    // 2.3开启倒计时
    this.setData({
      countDownVisible: true
    })
  },
  // 3.复制验证码到粘贴板
  copyCode() {
    wx.setClipboardData({
      data: my_Code,
    })
  },
  // 4.登录/注册
  async login() {
    const {
      mobile,
      code
    } = this.data
    // 4.1验证手机号和验证码
    if (!wx.verify.verifyMobile(mobile)) return
    if (!wx.verify.verifyCode(code)) return
    // 4.2调用登录/注册接口
    const res = await wx.http.post("/login", {
      mobile,
      code
    })
    if (res.code !== 10000) return wx.utils.toast('登录失败')
    // 4.3把token和refreshtoken 存储到本地和全局
    app.setToken(res.data.token)
    app.setRefreshToken(res.data.refreshToken)
    wx.utils.toast('登录成功')
    // 4.4重定向到开始要跳转的页面
    if (redirectURL === '/pages/my/index') {
      wx.switchTab({
        url: redirectURL,
      })
    } else {
      wx.redirectTo({
        url: redirectURL,
      })
    }

  }
})